import {
  fetchPerson,
  changeAvatar
} from '../../../api/user';
import {
  phoneEncryption
} from '../../../utils/util';
import Toast from 'tdesign-miniprogram/toast/index';
import Dialog from 'tdesign-miniprogram/dialog/index';
Page({
  data: {
    personInfo: {
      avatarUrl: '',
      nickName: '',
      gender: 0,
      phoneNumber: '',
    },
    showUnbindConfirm: false,
    pickerOptions: [{
        name: '男',
        code: '1',
      },
      {
        name: '女',
        code: '2',
      },
    ],
    typeVisible: false,
    genderMap: ['', '男', '女'],
  },
  onShow() {
    this.init();
  },
  onLoad() {
    this.init();
  },
  init() {
    this.fetchData();
  },
  fetchData() {
    fetchPerson().then((res) => {
      const {
        data,
        total = 0
      } = res.data
      console.log(data)
      this.setData({
        personInfo: data,
        'personInfo.phoneNumber': data.phoneNumber, //phoneEncryption()
      });
    });
  },
  onClickCell({
    currentTarget
  }) {
    const {
      dataset
    } = currentTarget;
    const {
      nickName,
      phoneNumber
    } = this.data.personInfo;

    switch (dataset.type) {
      case 'gender':
        this.setData({
          typeVisible: true,
        });
        break;
      case 'name':
        wx.navigateTo({
          url: `/pages/usercenter/name-edit/index?name=${nickName}`,
        });
        break;
      case 'avatarUrl':
        this.toModifyAvatar();
        break;
      case 'phoneNumber':
        wx.navigateTo({
          url: `/pages/usercenter/phone-edit/index?phone=${phoneNumber}`,
        });
        break;
      default: {
        break;
      }
    }
  },
  onClose() {
    this.setData({
      typeVisible: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e.detail;
    this.setData({
        typeVisible: false,
        'personInfo.gender': value,
      },
      () => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '设置成功',
          theme: 'success',
        });
      },
    );
  },
  onUnload() {
    wx.navigateBack({
      backRefresh: false
    });
  },
  async openUnbindConfirm() {
    const dialogConfig = {
      context: this,
      title: '《用户服务协议》',
      closeOnOverlayClick: true,
      content: '头像，户昵称，性别，用于站点显示用户名称;手机号司机联系你，除此之外不作其他用途',
      confirmBtn: '确定',
      cancelBtn: '取消',
    };

    Dialog.confirm(dialogConfig)
      .then(() => console.log('点击了确定'))
      .catch(() => console.log('点击了取消'));
  },
  async toModifyAvatar() {
    try {
      const tempFilePath = await new Promise((resolve, reject) => {
        wx.chooseMedia({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: (res) => {
            const {
              tempFilePath,
              size
            } = res.tempFiles[0];
            if (size <= 10485760) {
              changeAvatar({
                path: tempFilePath
              }).then(result => {
                if (result.data.code == 2000) {
                  resolve(result.data.data[1]);
                } else {
                  reject({
                    errMsg: '上传失败，请重新上传'
                  });
                }

              })
            } else {
              reject({
                errMsg: '图片大小超出限制，请重新上传'
              });
            }
          },
          fail: (err) => reject(err),
        });
      });
      Toast({
        context: this,
        selector: '#t-toast',
        message: `上传成功`,
        theme: 'success',
      });
      /*
      const tempUrlArr = tempFilePath.split('/');
      const tempFileName = tempUrlArr[tempUrlArr.length - 1];
      Toast({
        context: this,
        selector: '#t-toast',
        message: `已选择图片-${tempFileName}`,
        theme: 'success',
      });*/
    } catch (error) {
      if (error.errMsg === 'chooseImage:fail cancel') return;
      Toast({
        context: this,
        selector: '#t-toast',
        message: error.errMsg || error.msg || '修改头像出错了',
        theme: 'error',
      });
    }
  },
});